package com.ruoyi.receipt.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.CustomException;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class JwtUtils {
    private String key="KJHUhjjJYgYUllVbXhKDHXhkSyHjlNiVkYzWTBac1Yxkjhuad" ;
    private long ttl=-1 ;//时间请根据需求自己定义

    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles",roles);
        if (ttl > 0) {
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }
    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        try {
            return  Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(jwtStr)
                    .getBody();
        } catch (Exception e) {
           throw new CustomException("token解析错误");
        }
    }

    /**
     * 创建token
     * @param userId
     * @return
     */
    public String createToken(Long userId) {
        Map map=new HashMap();
        map.put("id",userId);
        map.put("randomSign",System.currentTimeMillis());
        String token=createJWT(UUID.randomUUID().toString(),JSONObject.toJSONString(map), "admin");
        return token;
    }

    /**
     * 创建token
     * @param token
     * @return
     */
    public String parseToken(String token) {
        Claims claims = parseJWT(token);
        JSONObject json = JSONObject.parseObject(claims.getSubject());
        Map<String, Object> map = (Map<String, Object>)json;
        return map.get("id")+"";
    }

}
